package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsAddressMapper;
import com.qiguliuxing.dts.db.domain.DtsAddress;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsAddressService {
	@Resource
	private DtsAddressMapper addressMapper;

	public List<DtsAddress> queryByUid(Integer uid) {
		QueryWrapper<DtsAddress> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsAddress::getUserId, uid);
		queryWrapper.eq("deleted", false);
		return addressMapper.selectList(queryWrapper);
	}

	public DtsAddress findById(Integer id) {
		return addressMapper.selectById(id);
	}

	public int add(DtsAddress address) {
		address.setAddTime(LocalDateTime.now());
		address.setUpdateTime(LocalDateTime.now());
		return addressMapper.insert(address);
	}

	public int update(DtsAddress address) {
		address.setUpdateTime(LocalDateTime.now());
		return addressMapper.updateById(address);
	}

	public void delete(Integer id) {
		addressMapper.deleteById(id);
	}

	public DtsAddress findDefault(Integer userId) {
		QueryWrapper<DtsAddress> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsAddress::getUserId, userId);
		queryWrapper.eq("deleted", false);
		return addressMapper.selectOne(queryWrapper);
	}

	/**
	 * 取消用户的默认地址配置
	 * 
	 * @param userId
	 */
	public void resetDefault(Integer userId) {
		DtsAddress address = new DtsAddress();
		address.setIsDefault(false);
		address.setUpdateTime(LocalDateTime.now());
		UpdateWrapper<DtsAddress> wrapper = new UpdateWrapper<>();
		wrapper.lambda().eq(DtsAddress::getUserId, userId);
		wrapper.eq("deleted", false);
		wrapper.lambda().eq(DtsAddress::getIsDefault, true);
		addressMapper.update(address, wrapper);
	}

	public List<DtsAddress> querySelective(Integer userId, String name, Integer page, Integer limit, String sort,
			String order) {
		QueryWrapper<DtsAddress> queryWrapper = new QueryWrapper<>();
		if (userId != null) {
			queryWrapper.lambda().eq(DtsAddress::getUserId, userId);
		}
		if (StrUtil.isNotEmpty(name)) {
			queryWrapper.like("name", name);
		}
		queryWrapper.eq("deleted", false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}

		IPage<DtsAddress> iPage = new Page<>(page, limit);
		iPage = addressMapper.selectPage(iPage, queryWrapper);
		return iPage.getRecords();
	}
}
